package models

import (
	"errors"
	"time"

	"golang.org/x/crypto/bcrypt"
)

type User struct {
	ID        int       `json:"id"`
	Name      string    `json:"name"`
	Email     string    `json:"email"`
	Password  string    `json:"password"`
	RoleId    int       `json:"role_id"`
	Role      Role      `json:"role"`
	UpdatedAt time.Time `json:"updated_at"`
	CreatedAt time.Time `json:"created_at"`
}

func GetAllUser() (users []User, err error) {
	err = db.Find(&users).Error

	return
}

func AddUser(user User) error {
	err := db.Create(&user).Error

	return err
}

func UpdateUser(id int, data map[string]interface{}) (err error) {
	err = db.Model(&User{}).Where("id = ?", id).Updates(data).Error

	return
}

func DelUser(id int) error {
	err := db.Where("id = ?", id).Delete(User{}).Error

	return err
}

func UserIsExist(name string) bool {
	var user User
	db.Select("id").Where("name =?", name).First(&user)

	return user.ID > 0
}

func GetUserById(id int) (user User, err error) {
	err = db.Where("id =?", id).First(&user).Error

	return
}

func GetUsers(keyword string, pageNum int, pageSize int) (users []User, total int64, err error) {
	query := db.Select("id,name,role_id,created_at,email")
	if keyword != "" {
		query.Where("name LIKE ? or email LIKE ?", keyword+"%", keyword+"%")
	}

	err = query.Preload("Role").Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&users).Error
	if err != nil {
		return
	}

	err = query.Model(&users).Count(&total).Error

	return
}

// CheckLogin 后台登录验证
func CheckUserAuth(email string, password string) (user User, err error) {
	err = db.Where("email = ?", email).First(&user).Error
	if err != nil {
		return
	}

	if user.ID < 1 {
		err = errors.New("用户不存在")
		return
	}

	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))

	return
}

func ResetPwd(id int, pwd interface{}) error {
	err := db.Model(User{}).Where("id =?", id).Update("password", pwd).Error

	return err
}
